const jwt = require("jsonwebtoken");
const { UnauthorizedError } = require("../utils/errors");
const { failure } = require("../utils/responses");

module.exports = async (req, res, next) => {
  try {
    const { token } = req.headers;
    if (!token) {
      throw new UnauthorizedError("Token is missing");
    }
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const { userId } = decoded;
    req.userId = userId;
    return next();
  } catch (err) {
    return failure(res, err);
  }
};
